package com.sharecar.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;

import com.android.sharecar.model.ProvideRideMsg;
import com.sharecar.db.DB;

public class ProvideRideMsgService {
	private static ProvideRideMsgService service;

	private ProvideRideMsgService() {
	}

	public static ProvideRideMsgService getInstance() {
		if (null == service) {
			service = new ProvideRideMsgService();
		}
		return service;
	}

	public void addRequest(ProvideRideMsg requestMsg) {
		Connection conn = DB.getConn();
		try {
			conn.setAutoCommit(false);
		} catch (SQLException e1) {
			e1.printStackTrace();
		}

		String sql = "insert into PickRideRequests values (null, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
		PreparedStatement pstmt = DB.prepare(conn, sql);
		try {
			pstmt.setString(1, requestMsg.getStartPlace());
			pstmt.setString(2, requestMsg.getEndPlace());
			pstmt.setDouble(3, requestMsg.getStartLocation().getLongitude());
			pstmt.setDouble(4, requestMsg.getStartLocation().getLatitude());
			pstmt.setDouble(5, requestMsg.getEndLocation().getLongitude());
			pstmt.setDouble(6, requestMsg.getEndLocation().getLatitude());
			pstmt.setInt(7, requestMsg.getProvideSeats());
			pstmt.setTimestamp(8, new Timestamp(requestMsg.getPostTime()
					.getTime()));
			pstmt.setInt(9, requestMsg.getUser().getUserId());

			pstmt.executeUpdate();
			conn.commit();
		} catch (SQLException e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try {
				conn.setAutoCommit(true);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			DB.close(pstmt);
			DB.close(conn);
		}
	}
}
